var apiUrl = $("#apiUrl").val();
var userType = $("#userType").val();
var localIsDispaxth = 0;


var Manufacturer_select = [];
var Maintainer_select = [];


$(document).ready(function (){
    menuCss("维修");
    $("#queryForm").find("[name='hospitalId']").val(null);
    $("#queryForm").find("[name='hospitalId']").select2({
        language: 'zh-CN',
        placeholder: '医院',
        allowClear: true});
    $("#filter-status").val(null);
    $("#filter-status").select2({
        language: 'zh-CN',
        placeholder: '状态',
        allowClear: true});
    $("#queryForm").find("[name='urgentDegree']").val(null);
    $("#queryForm").find("[name='urgentDegree']").select2({
        language: 'zh-CN',
        placeholder: '紧急程度',
        allowClear: true});
    $("#queryForm").find("[name='manufacturerId']").val(null);
    $("#queryForm").find("[name='manufacturerId']").select2({
        language: 'zh-CN',
        placeholder: '厂商',
        allowClear: true});
    $("#queryForm").find("[name='maintainerId']").val(null);
    $("#queryForm").find("[name='maintainerId']").select2({
        language: 'zh-CN',
        placeholder: '服务商',
        allowClear: true});

    // 初始化复选框
    $('input[type="checkbox"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });
    initQueryTerm();
    getRepairList();
    $("#show-count").change(function(){
        getRepairList();
    })
    
    $("#emptyHospitalName").click(function (){
        $("#addRepairForm").find("[name='hospitalName']").val("");
        $("#addRepairForm").find("[name='hospitalId']").val("");
    });
    $("#emptyDeviceName").click(function (){
        $("#addRepairForm").find("[name='deviceName']").val("");
        $("#addRepairForm").find("[name='deviceId']").val("");
    });
    $("#addRepairForm").find("[name='serviceName']").typeahead({
        source: function (query, process) {
            var url = apiUrl + "base/queryHospitalMaintainer";
            var hospitalId =null;
            if(userType == 1104){
                hospitalId = $("#addRepairForm").find("[name='hospitalId']").val();
            }else{
                hospitalId = $("#hospitalId").val();
            }
            if(hospitalId){
                publicAjax(url,"POST",{hospitalId : hospitalId, name: query,serviceType:2901},function (data){
                    if(data.ret == 200){
                        if(data.data == null || data.data.length == 0 ){
                            return process(new Array());
                        }
                        return  process(data.data);
                    }
                });
            }        
        },
        updater: function (item) {
            $("#addRepairForm").find("[name='serviceId']").val(item.serviceId);
            $("#addRepairForm").find("[name='serviceContacts']").val(item.serviceContacts);
            $("#addRepairForm").find("[name='servicePhone']").val(item.servicePhone);
            return this.$element.val().replace(new RegExp(this.query + '$'),'') + item.name ;
        }
    });
    $("#assignForm").find("[name='serviceName']").typeahead({
        source: function (query, process) {
            var url = apiUrl + "base/queryHospitalMaintainer";
            var hospitalId =null;
            if(userType == 1104){
                hospitalId = $("#addRepairForm").find("[name='hospitalId']").val();
            }else{
                hospitalId = $("#hospitalId").val();
            }
            if(hospitalId){
                publicAjax(url,"POST",{hospitalId : hospitalId, name: query,serviceType:2901},function (data){
                    if(data.ret == 200){
                        if(data.data == null || data.data.length == 0 ){
                            return process(new Array());
                        }
                        return  process(data.data);
                    }
                });
            }        
        },
        updater: function (item) {
            $("#addRepairForm").find("[name='serviceId']").val(item.serviceId);
            $("#addRepairForm").find("[name='serviceContacts']").val(item.serviceContacts);
            $("#addRepairForm").find("[name='servicePhone']").val(item.servicePhone);
            return this.$element.val().replace(new RegExp(this.query + '$'),'') + item.name ;
        }
    });
    /*$("#assign-model").find("[name='engineerName']").blur(function (){
        engineerNameBlur(this);
    });*/
    $("[name='addPart']").click(function (){
        $("#addPart-modal").iziModal("open",this);
    });
    $("#addPart").click(function (){
        /*addPartInfo();
        $("#addPart-modal").iziModal("close",this);*/
        checkAddPartInfo();
    });
    $("#savePart").click(function (){
        savePart();
    })
    var localServiceId = null;
    $("#chooseDevice").click(function (){
        var json = {};
        json.root = apiUrl;
        $("#deviceDvie").device({root:apiUrl,callback:function (data){
            var deviceName = data.deviceName;
            $("#addRepairForm").find("[name='deviceId']").val(data.deviceId);
            $("#addRepairForm").find("[name='deviceName']").val(data.deviceName);
            $("#addRepairForm").find("[name='hospitalId']").val(data.hospitalId || '');
            $("#addRepairForm").find("[name='hospitalName']").val(data.hospitalName || '');
            publicAjax(apiUrl+"repair/queryDeviceIsRepair","POST",{deviceId:data.deviceId},function(res){
                if(res.ret == 200){
                    if(res.data == 1){
                        flavrShowByTime("该设备正在维修中",null,"info",null);
                    }
                }
            })
            var url = apiUrl + "repair/queryInfoPage";
            publicAjax(url,"POST",{deviceId:data.deviceId},function (data){
                console.log(data)
                console.log(3333)
                if(data.ret == 200){
                    if(data.data){
                        if(data.data.manufacturer != null){
                            $("#manufacturerDiv").find("[name='manufacturerName']").val(data.data.manufacturer.manufacturerName);
                            $("#addManufacturerId").val(data.data.manufacturer.manufacturerId);
                            $("#manufacturerDiv").show();
                            $("#addRepairForm input[value='1102']").parents("label").show();
                         }else{
                            $("#manufacturerDiv").hide();
                            $("#addRepairForm input[value='1102']").parents("label").hide();
                         }
                        if(data.data.supplier != null){
                            $("#supplierDiv").show();
                            $("#addRepairForm input[value='1105']").parents("label").show();
                            $("#supplierDiv").find("[name='supplierName']").val(data.data.supplier.supplierName);
                            $("#addSupplierId").val(data.data.supplier.supplierId);
                        }else{//如果没有经销商，则隐藏经销商单选款和input框
                            $("#supplierDiv").hide();
                            $("#addRepairForm input[value='1105']").parents("label").hide();
                        }
                        $("[name='serviceType'][value='"+data.data.serviceType+"']").iCheck("check");
                        if(data.data.serviceType == 1103){
                            $("#maintainerDiv").show();
                            $("#supplierDiv").hide();
                            $("#manufacturerDiv").hide();
                            localServiceId = null;
                        }else if(data.data.serviceType == 1102){
                            $("#manufacturerDiv").show();
                            $("#maintainerDiv").hide();
                            $("#supplierDiv").hide();
                            localServiceId = data.data.manufacturer.manufacturerId;
                        }else if(data.data.serviceType == 1105){
                            $("#manufacturerDiv").hide();
                            $("#maintainerDiv").hide();
                            $("#supplierDiv").show();
                            localServiceId = data.data.supplier.supplierId;
                        }else{
                            $("#manufacturerDiv").hide();
                            $("#maintainerDiv").hide();
                            $("#supplierDiv").hide();
                            localServiceId = null
                        }
                    }
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                }
            });
        }});
    });

    $("#chooseHospital").click(function (){
        var json = {};
        json.root = apiUrl;
        $("#hospitalDvie").hospital({root:apiUrl,callback:function (data){
            var hospital = data.getSelectedData();
            $("#addRepairForm").find("[name='hospitalId']").val(hospital.hospitalId);
            $("#addRepairForm").find("[name='hospitalName']").val(hospital.hospitalName);
        }});
    });
    var boolAdd = false;
    $("#saveAddRepair").click(function(){
        var submitServiceName = '';
        if($("#addRepairForm input[name='serviceType']:checked").val() == 1103){
            localServiceId = null;
            submitServiceName = $("#addServiceName").val();
        }else if($("#addRepairForm input[name='serviceType']:checked").val() == 1102){
            submitServiceName = $("#manufacturerDiv input[name='manufacturerName']").val();
            localServiceId = $("#addManufacturerId").val()
        }else if($("#addRepairForm input[name='serviceType']:checked").val() == 1105){
            submitServiceName = $("#supplierDiv input[name='supplierName']").val();
            localServiceId = $("#addSupplierId").val()
        }else{
            submitServiceName = '';
            localServiceId = null;
        }
        var submitRepair = {
            deviceId: $("#repairDeviceId").val(),
            faultDepictHospital: $("#faultDescription").val(),
            faultTime: $("#faultTime").val(),
            deviceStatus: $("#addDeviceStatus").val(),
            fileIds: $("#addRepairFileIds").val(),
            serviceId: localServiceId,
            serviceType: $("#addRepairForm input[name='serviceType']:checked").val(),
            hospitalId: $("#repairHospitalId").val(),
            repairPerson: $("#addRepairPerson").val(),
            repairPersonPhone: $("#addRepairPhone").val(),
            engineerName: $("#addEngineer").val(),
            engineerPhone: $("#addEngineerPhone").val(),
            serviceName: submitServiceName,
            serviceContacts: $("#addServiceContacts").val(),
            servicePhone: $("#addServicePhone").val(),
            isDispatch: $("input[name='isDispatch']:checked").val(),
            remark: $("#addRepairForm input[name='remark']").val()
        }
        if(!$("#repairDeviceId").val()){
            flavrShowByTime("请选择设备",null,"danger",false);
            return;
        }else if(!$("#repairHospitalId").val() && userType == 1104){
            flavrShowByTime("请选择医院",null,"danger",false);
            return;
        }else if(!$("#addDeviceStatus").val()){
            flavrShowByTime("请选择设备状态",null,"danger",false);
            return;
        }else if(!$("#faultTime").val()){
            flavrShowByTime("请选择故障时间",null,"danger",false);
            return;
        }else if(!$("#addRepairPerson").val()){
            flavrShowByTime("请填写报修人",null,"danger",false);
            return;
        }else if(!$("#addRepairPhone").val()){
            flavrShowByTime("请填写报修人电话",null,"danger",false);
            return;
        }else{
            if($("input[name='isDispatch']:checked").val() == 1){
                if(!$("#addEngineer").val()){
                    flavrShowByTime("请填写工程师",null,"danger",false);
                    return;
                }else if(!$("#addEngineerPhone").val()){
                    flavrShowByTime("请填写工程师电话",null,"danger",false);
                    return;
                }
            }
            if(!boolAdd){
                boolAdd = true;
                isFileUpload($("#addRepairForm"),function (data){
                    var fileIdStr = [];
                    for(var x=0;x<data.length;x++){
                        fileIdStr.push(data[x].fileId);
                    }
                    $("#addRepairFileIds").val(fileIdStr.join(","));
                    var url=apiUrl+"repair/add";
                    submitRepair.fileIds = $("#addRepairFileIds").val();
                    publicAjax(url,"POST",submitRepair,function (data){
                        if(data.ret == 200){
                            flavrShowByTime(data.msg,null,"success",false);
                            $("#add-repair-modal").iziModal("close",this);
                            isFileUpload($("#addRepairForm"),function (data){

                            })
                            getRepairList();
                        }else{
                            flavrShowByTime(data.msg,null,"danger",false);
                        }
                        boolAdd =false;
                    });
                });
            }          
        }       
    })
    $("#saveExamineMaintainer").click(function (){
        saveExamineMaintainer();
    });
});

function checkAddPartInfo(){
    var reg = /^[0-9]\d*(\.\d{1,2})?$/;
    var oldPartPrice = $("#addPart-modal").find("[name='oldPartPrice']").val();
    if(oldPartPrice != null && oldPartPrice != ''){
        if(!reg.test(oldPartPrice)){
            flavrShowByTime("请输入正确格式的旧备件价格。",null,"danger",false);
            return;
        }else{
            oldPartPrice = oldPartPrice *100;
        }
    }
    var newPartPrice = $("#addPart-modal").find("[name='newPartPrice']").val();
    if(newPartPrice != null && newPartPrice != ''){
        if(!reg.test(newPartPrice)){
            flavrShowByTime("请输入正确格式的新备件价格。",null,"danger",false);
            return;
        }else{
            newPartPrice = newPartPrice *100;
        }
    }

    isFileUpload($("#newFileForm"),function (fileLists){
        var oldFileList = null;
        var newFileList = null;
        isFileUpload($("#oldFileForm"),function (fileList){
            if(fileLists != null && fileLists.length>0){
                newFileList = fileLists;
            }
            if(fileList != null && fileList.length>0){
                oldFileList = fileList;
            }
            addPartInfo(oldPartPrice,newPartPrice,oldFileList,newFileList);
        });
    });
}

// 打开分配服务商的model
var localRepairId,localDeviceId,localStatus,localAssignServiceId,serviceName,serviceContacts,servicePhone,globalServiceType;
function openAssignModel(){
    if($("input[name='one']:checked").length){
        localRepairId = $("input[name='one']:checked").val();
        localDeviceId = $("input[name='one']:checked").attr("deviceId");
        localStatus = $("input[name='one']:checked").attr("status");
        if(localStatus == "2200"){//只能是待处理状态下才能分配
            if(localDeviceId != 'null'){
                $("#assign-model").iziModal("open",this);
                getBaseInfo();
            }else {
                $("#assign_model_Two").iziModal("open",this);
                get_info()
            }



        }else{
            flavrShowByTime("只有待处理状态下才能分配",null,"danger",null);
        }
    }else{
        flavrShowByTime("请选择一条维修记录",null,"danger",null);
    }  
}


//获取厂商
function get_ManufacturerList() {
    publicAjax(apiUrl + "base/queryManufacturer","POST",{},function (data){
        console.log(data);
        if(data.ret == 200){
            var list = data.data;
            Manufacturer_select = list;
            var str = '<option value=""></option>';
            $.each(list,function (key,val) {
                str += '<option value="'+val.manufacturerId+'">'+val.manufacturerName+'</option>'
            })
            $('#assign_model_Two').find('#Manufacturer_select').html(str);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}

//获取维修商
function get_MaintainerList() {
    publicAjax(apiUrl + "base/queryMaintainer","POST",{},function (data){
        if(data.ret == 200){
            var list = data.data;
            Maintainer_select = data.data;
            var str = '<option value=""></option>';
            $.each(list,function (key,val) {
                str += '<option value="'+val.maintainerId+'">'+val.maintainerName+'</option>'
            })
            $('#assign_model_Two').find('#Maintainer_select').html(str);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}

//获取维修处理信息
function get_info() {
    publicAjax(apiUrl + "repair/details","POST",{repairId:$("input[name='one']:checked").val()},function (data){
        if(data.ret == 200){
            var obj = data.data;
            console.log(obj);
            $('#assign_model_Two').find("#hospitalName").text(obj.hospitalName);
            $('#assign_model_Two').find("#address").text(obj.address);
            $('#assign_model_Two').find("#remark").text(obj.remark);
            $('#assign_model_Two').find("#linkman").text(obj.repairPerson);
            $('#assign_model_Two').find("#phoneNumber").text(obj.repairPersonPhone);
            $('#assign_model_Two').find("#malfunctionTime").text(obj.faultTime);
            $('#assign_model_Two').find("#brand").text(obj.brand);
            $('#assign_model_Two').find("#faultDepictHospital_Two").val(obj.faultDepictHospital);



            if(obj.voice == ''){
                $('#assign_model_Two').find("#Is_Hidden_Two").hide();
                $('#IF_Box').html('<span id="linkman">'+obj.repairPerson+'</span>')
            }else {
                $('#assign_model_Two').find("#Is_Hidden_Two").show();
                $('#assign_model_Two').find("#Audio_Box_Two").attr('src',obj.voice)
                $('#IF_Box').html('<input type="text" class="form-control" name="" id="" value="'+obj.repairPerson+'">')
            }



            if(obj.engineerPhone == null){
                $('#assign_model_Two').find("#NO").iCheck("check");
            }else {
                $('#assign_model_Two').find("#YES").iCheck("check");
                $('#assign_model_Two').find("#dispatch_Div").show();
                $('#assign_model_Two').find("#dispatch_Div").find('#engineerName_two').val(obj.engineer);
                $('#assign_model_Two').find("#dispatch_Div").find('#engineerPhone_two').val(obj.engineerPhone);

            }


            var list1 = obj.fileList;
            var str1 = '';
            var str2 = '';
            $.each(list1,function (key,val) {
                if(val.fileTypeName == '设备图片'){
                    str1 += '<img src="'+val.fileUrl+'" alt="" style="width: 20%; background-color:#ccc; height: 100px; margin: 2px">';
                }else {
                    str2 += '<img src="'+val.fileUrl+'" alt="" style="width: 20%; background-color:#ccc; height: 100px; margin: 2px">';
                }
            })
            if(str1 == ''){
                str1 = '<p style="margin-left: 20px">暂无数据</p>'
            }
            if(str2 == ''){
                str2 = '<p style="margin-left: 20px">暂无数据</p>'
            }
            $('#box_img_one').html(str1);
            $('#box_img_two').html(str2);
            $('#box_img_one').find("img").viewer();
            $('#box_img_two').find("img").viewer();
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}



//保存维修处理信息
function save_info() {
    var data = {};
    data.repairId = $("input[name='one']:checked").val();
    data.isDispatch = $("input[name='is_dispatch']:checked").val();
    if($('#assign_model_Two').find("input[name='is_dispatch']:checked").val() == 1){
        data.engineerName = $('#assign_model_Two').find('#engineerName_two').val();
        data.engineerPhone = $('#assign_model_Two').find('#engineerPhone_two').val();
        if(data.engineerName == '' || data.engineerPhone == ''){
            flavrShowByTime('请注意负责人姓名跟电话填写正常',null,'danger',false);
            return
        }
    }

    data.serviceType = $('#assign_model_Two').find("input[name='serviceType']:checked").val();


    if($('#assign_model_Two').find("input[name='serviceType']:checked").val() == 1102){

        data.serviceId = $('#assign_model_Two').find("#Manufacturer_select").val();
        data.serviceName = $('#assign_model_Two').find("#Manufacturer_select").find('option:selected').text();
        data.serviceContacts = $('#assign_model_Two').find("#Manufacturer_Linkman").text();
        data.servicePhone = $('#assign_model_Two').find("#Manufacturer_Phone").text();
        if(data.serviceId == ''){
            flavrShowByTime('请选择厂商',null,'danger',false);
            return
        }

    }
    if($('#assign_model_Two').find("input[name='serviceType']:checked").val() == 1103){

        data.serviceId = $('#assign_model_Two').find("#Maintainer_select").val();
        data.serviceName = $('#assign_model_Two').find("#Maintainer_select").find('option:selected').text();
        data.serviceContacts = $('#assign_model_Two').find("#Maintainer_Linkman").text();
        data.servicePhone = $('#assign_model_Two').find("#Maintainer_Phone").text();
        if(data.serviceId == ''){
            flavrShowByTime('请选择维修商',null,'danger',false);
            return
        }

    }

    data.faultDepictHospital = $('#assign_model_Two').find('#faultDepictHospital_Two').val();
    data.repairPerson = $('#assign_model_Two').find('#IF_Box input').val();
    console.log(data);



    publicAjax(apiUrl + "repair/distribution","POST",data,function (data){
        console.log(data);
        if(data.ret == 200){
            flavrShowByTime('操作成功',null,"success",false);
            $("#assign_model_Two").iziModal("close",this);
            getRepairList();
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}




var isCheckMaintainer = false;//是否需要审核维修商
function getBaseInfo(){
    publicAjax(apiUrl + "repair/queryInfoPage","POST",{deviceId: localDeviceId, repairId: localRepairId},function (data){
        console.log(data);
        console.log(4444);
        if(data.ret == 200){
            if(data.data){
                if(data.data.manufacturer != null){
                    $("#assignManufacturerDiv").find("[name='manufacturerName']").val(data.data.manufacturer.manufacturerName);
                    $("#assignManufacturerDiv").find("[name='manufacturerId']").val(data.data.manufacturer.manufacturerId);
                }else{//如果没有厂商则不能选择厂商
                    $("#assignForm input[value='1102']").parents("label").hide();
                 }
                if(data.data.supplier != null){
                    $("#assignSupplierDiv").find("[name='supplierName']").val(data.data.supplier.supplierName);
                    $("#assignSupplierDiv").find("[name='supplierId']").val(data.data.supplier.supplierId);
                }else{//如果没有经销商则不能选择
                    $("#assignForm input[value='1105']").parents("label").hide();
                }

                if(data.data.voice == null){
                    $('#Is_Hidden').hide();
                }else {
                    //音频播放
                    $('#assign-model').find('#Audio_Box').attr('src',data.data.voice);
                    console.log($('#assign-model').find('#Audio_Box'))
                }



                $('#assign-model').find('#faultDepictHospital').val(data.data.faultDepictHospital);
                $("#FaultTime_Two").html(data.data.faultTime);
                $("#hospitalContactsSpan").html(data.data.repairPerson ||'');
                $("#hospitalPhoneSpan").html(data.data.repairPersonPhone);






                $("#assignServiceDiv").find("[name='serviceType'][value='"+data.data.serviceType+"']").iCheck("check");
                if(data.data.serviceType == 1103){//维修商
                    /*$("#assignMaintainerDiv").show();
                    $("#assignSupplierDiv").hide();
                    $("#assignManufacturerDiv").hide();*/
                    $("#assignServiceDiv").hide();
                    $("#assignForm input[value='0']").parents("label").hide();//如果是维修商必须选择指派工程师
                    $("#assignForm input[value='1']").iCheck("check");
                    localIsDispaxth = 1;
                    $("#dispatchDiv").show();
                    globalServiceType = data.data.serviceType;
                }else if(data.data.serviceType == 1102){//厂商
                    /*$("#assignManufacturerDiv").show();
                    $("#assignMaintainerDiv").hide();
                    $("#assignSupplierDiv").hide();*/
                    $("#assignServiceDiv").hide();
                    $("#assignForm").find("[name='serviceId']").val(data.data.manufacturer.manufacturerId);
                    $("#assignForm input[name='0']").show();
                    $("#assignForm input[name='0']").iCheck("check");
                    $("#dispatchDiv").hide();
                    globalServiceType = data.data.serviceType;
                }else if(data.data.serviceType == 1105){//经销商
                    /*$("#assignManufacturerDiv").hide();
                    $("#assignMaintainerDiv").hide();
                    $("#assignSupplierDiv").show();*/
                    $("#assignServiceDiv").hide();
                    $("#assignForm").find("[name='serviceId']").val(data.data.supplier.supplierId);
                    $("#assignForm input[value='0']").parents("label").show();
                    $("#assignForm input[value='0']").iCheck("check");
                    $("#dispatchDiv").hide();
                    globalServiceType = data.data.serviceType;
                }else{
                    $("#assignServiceDiv").show();
                    $("#assignManufacturerDiv").hide();
                    $("#assignMaintainerDiv").show();
                    $("#assignSupplierDiv").hide();
                    $("#assignServiceDiv [name='serviceType'][value='1103']").iCheck("check");
                    // globalServiceType = 1103;
                    $("#assignForm input[value='0']").parents("label").hide();//如果没有选择服务商，则默认是维修商
                    $("#assignForm input[value='1']").iCheck("check");
                    localIsDispaxth = 1;
                    $("#dispatchDiv").show();
                }
                serviceName = data.data.serviceName || '';
                serviceContacts = data.data.serviceContacts || '';
                servicePhone = data.data.servicePhone || '';
                $("#assignForm input[name='serviceName']").val(serviceName);
                $("#assignForm input[name='serviceContacts']").val(serviceContacts);
                $("#assignForm input[name='servicePhone']").val(servicePhone);
                switch (globalServiceType){
                    case 1102:
                        //厂商
                        $("#serviceCompanySpan").html("厂商: "+data.data.manufacturer.manufacturerName || "");
                        $("#serviceNameSpan").html(data.data.manufacturer.manufacturerContacts || "");
                        $("#servicePhoneSpan").html(data.data.manufacturer.manufacturerPhone || "");
                        break;
                    case 1105:
                        //经销商
                        $("#serviceCompanySpan").html("经销商: "+data.data.supplier.supplierName);
                        $("#serviceNameSpan").html(data.data.supplier.supplierContacts || "");
                        $("#servicePhoneSpan").html(data.data.supplier.supplierPhone || "");
                        break;
                    case 1103:
                        //维修商
                        $("#serviceCompanySpan").html("维修商: "+serviceName);
                        $("#serviceNameSpan").html(serviceName);
                        $("#servicePhoneSpan").html(servicePhone);
                        //医院端选择的维修商需要审核。。。这里是添加审核按钮
                        if(data.data.examine == null && data.data.serviceType==1103){
                            isCheckMaintainer = true;//
                            var buttonHtml = "<button type='button' class='btn btn-info btn-sm' data-toggle='tooltip' onclick='bindServiceInfo(\""+localRepairId+"\",\""+serviceName+"\",\""+serviceContacts+"\",\""+servicePhone+"\")'>审核</button>";
                            $("#serviceCompanySpan").append("&nbsp;&nbsp;").append(buttonHtml);
                        }
                        break;
                    default :
                        //无
                        $("#serviceCompanySpan").html("医院没有选择服务商");
                        $("#serviceNameSpan").html(serviceName);
                        $("#servicePhoneSpan").html(servicePhone);
                }
                $("#examineTr").html("");
                var examine = data.data.examine;
                var examineComment = data.data.examineComment || '';
                if(examine != null ){
                    var html = "";
                        if(examine == 1){
                            html = "<td class='text-muted' style='text-align: right'>审核结果：</td><td class='text-muted' style='text-align: left'>通过</td>"+
                            "<td class='text-muted' style='text-align: right'>审核说明：</td><td class='text-muted' style='text-align: left'>"+examineComment+"</td>";
                            $("[name='is_dispatch'][value='1']").iCheck("check");
                            $("#dispatchDiv").show();
                        }else if(examine == 0){
                            html = "<td class='text-muted' style='text-align: right'>审核结果：</td><td class='text-muted' style='text-align: left'>不通过</td>"+
                                "<td class='text-muted' style='text-align: right'>审核说明：</td><td class='text-muted' style='text-align: left'>"+examineComment+"</td>";
                            $("#assignServiceDiv").show();
                        }
                    $("#examineTr").html(html);
                }
                //如果有工程师或工程师联系方式，则默认选择指派工程师
                if(data.data.engineerName || data.data.engineerPhone){
                    $("#assignForm input[value='1']").iCheck("check");
                    localIsDispaxth = 1;
                    $("#engineerName").val(data.data.engineerName || '');
                    $("#engineerPhone").val(data.data.engineerPhone || '');
                    $("#dispatchDiv").show();
                }


                var imgList = data.data.fileList;
                var imgStr = '';

                if(imgList.length > 0){
                    $.each(imgList,function (key,val) {
                        imgStr += '<img src="'+val.fileUrl+'" alt="" style="width: 20%; background-color:#ccc; height: 100px; margin: 2px">';
                    })
                }else {
                    imgStr = '<p style="margin-left: 20px">暂无数据</p>'
                }



                $('#assign-model #img_box_one').html(imgStr);
                $('#assign-model #img_box_one').find("img").viewer();


            }
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}
function improveInfo(){
    if($("input[name='one']:checked").length){
        localRepairId = $("input[name='one']:checked").val();
        localDeviceId = $("input[name='one']:checked").attr("deviceId");
        localStatus = $("input[name='one']:checked").attr("status");
        if(localStatus == "2202"){//只能是待维修、待指派、待工程师处理状态下才能补全信息
            $("#improve-model").iziModal("open",this);
        }else{
            flavrShowByTime("待维修状态下才能补全信息",null,"danger",null);
        }
    }else{
        flavrShowByTime("请选择一条维修记录",null,"danger",null);
    }
}
//分配提交
var isAssign = false;
function submitAssign(){
    if(!isCheckMaintainer){
        $('#assignForm').bootstrapValidator('validate');
        if($('#assignForm').data('bootstrapValidator').isValid()){
            if(!isAssign){
                isAssign = true
                if(globalServiceType == 1103){//维修商没有seviceId
                    $("#assignServiceDiv").find("[name='serviceId']").val(null);
                    serviceId = null;
                    serviceName = $("#assignForm input[name='serviceName']").val();
                    servicePhone = $("#assignForm input[name='servicePhone']").val();
                    serviceContacts = $("#assignForm input[name='serviceContacts']").val();
                    localIsDispaxth = 1;
                }else if(globalServiceType == 1105){//厂商和经销商没有维修商信息
                    serviceId = $("#assignSupplierDiv input[name='supplierId']").val();
                    serviceName = $("#assignSupplierDiv input[name='supplierName']").val();
                    servicePhone = null;
                    serviceContacts = null;
                }else if(globalServiceType == 1102){
                    serviceId = $("#assignManufacturerDiv input[name='manufacturerId']").val();
                    serviceName = $("#assignManufacturerDiv input[name='manufacturerName']").val();
                    servicePhone = null;
                    serviceContacts = null;
                }else{
                    serviceId = null;
                }
                var submitData = {
                    repairId: localRepairId,
                    serviceId: $("#assignServiceDiv").find("[name='serviceId']").val(),
                    isDispatch: localIsDispaxth,
                    serviceId: serviceId,
                    serviceName: serviceName,
                    serviceType: globalServiceType || $("#assignForm input[name='serviceType']:checked").val(),
                    servicePhone: servicePhone,
                    serviceContacts: serviceContacts,
                    /*dispatchTime: localIsDispaxth == 1 ? $("#dispathTime").val(): null,*/
                    hospitalContacts: localIsDispaxth == 1 ? $("#hospitalContacts").val() : null,
                    hospitalPhone: localIsDispaxth == 1 ? $("#hospitalPhone").val() : null,
                    engineerName: localIsDispaxth == 1 ? $("#engineerName").val() : null,//负责人
                    engineerPhone: localIsDispaxth == 1 ? $("#engineerPhone").val() : null,//负责人电话
                    faultDepictHospital: $('#faultDepictHospital').val()
                }
                console.log(submitData)
                publicAjax(apiUrl+"repair/distribution","POST",submitData,function (data) {
                    if(data.ret == 200){
                        flavrShowByTime("操作成功",null,"success",null);
                        $("#assign-model").iziModal("close");
                        getRepairList();
                    }else{
                        flavrShowByTime(data.msg,null,"danger",null);
                    }
                    isAssign = false;
                })
            }        
        }
    }else{
        flavrShowByTime("请先审核维修商",null,"danger",null);
    }
}

//补全信息提交
var boolImprove = false;
function improveConfirm(){
    $("#improveRepairId,#repairIdOne,#repairIdTwo,#repairIdThree").val(localRepairId);
    $("#improveDeviceId").val(localDeviceId);
    $('#improve-form').bootstrapValidator('validate');
    if($('#improve-form').data('bootstrapValidator').isValid()){
        if(!boolImprove){
            boolImprove = true;
            isFileUpload($("#improve-one"),function (data){
                var fileIdStr = [];
                for(var x=0;x<data.length;x++){
                    fileIdStr.push(data[x].fileId);
                }
                $("#improveOneFileIds").val(fileIdStr.join(","));
            });
            isFileUpload($("#improve-two"),function (data){
                var fileIdStr = [];
                for(var x=0;x<data.length;x++){
                    fileIdStr.push(data[x].fileId);
                }
                $("#improveTwoFileIds").val(fileIdStr.join(","));
            });
            isFileUpload($("#improve-three"),function (data){
                var fileIdStr = [];
                for(var x=0;x<data.length;x++){
                    fileIdStr.push(data[x].fileId);
                }
                $("#improveThreeFileIds").val(fileIdStr.join(","));
            });
            var fildStrs = [];
            if($("#improveOneFileIds").val()){
                fildStrs.push($("#improveOneFileIds").val());
            }
            if($("#improveTwoFileIds").val()){
                fildStrs.push($("#improveTwoFileIds").val());
            }
            if($("#improveThreeFileIds").val()){
                fildStrs.push($("#improveThreeFileIds").val());
            }
            $("#improveFileIds").val(fildStrs.join(","));
            var url=apiUrl+"repair/saveRepairData";
            publicAjax(url,"POST",$("#improve-form"),function (data){
                if(data.ret == 200){
                    flavrShowByTime(data.msg,null,"success",false);
                    $("#improve-model").iziModal("close",this);
                    getRepairList();
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                }
                boolImprove =false;
            });
        }
    }
}

//添加事件提交按钮
var boolEvent = false;
function eventConfirm(){
    $("#eventRepairId").val(localRepairId);
    $('#event-form').bootstrapValidator('validate');
    if($('#event-form').data('bootstrapValidator').isValid()){
        if(!boolEvent){
            boolEvent = true;
            //var url=apiUrl+"/event/addEvent";
            isFileUpload($("#event-form"),function (data){
                var fileIdStr = [];
                for(var x=0;x<data.length;x++){
                    fileIdStr.push(data[x].fileId);
                }
                $("#eventFileIds").val(fileIdStr.join(","));
                var url=apiUrl+"/event/addEventForWeChat";
                publicAjax(url,"POST",$("#event-form"),function (data){
                    if(data.ret == 200){
                        flavrShowByTime(data.msg,null,"success",false);
                        $("#event-model").iziModal("close",this);
                        getRepairList();
                    }else{
                        flavrShowByTime(data.msg,null,"danger",false);
                    }
                    boolEvent =false;
                });
            });
        }
    }
}

function isFileUpload(form,fn){
    var flag = false;
    var url = apiUrl + "fileUpload/fileUploadForWeChat";
    $($(form).find("[name='files']")).each(function (){
        if($(this).val()!= ""){
            flag=true;
        }
    })
    if(flag){
        fileUplod(url,$(form),function (fileList){
                fn(fileList);
        });
    }else{
        fn([]);
    }
}

//获取设备信息
function getDeviceInfo(id){
    publicAjax(apiUrl+"base/queryManufacturerByDeviceId","POST",{deviceId: id},function (data) {
        if(data.ret == 200){
            $("#deviceNameSpan").html(data.data.deviceName || '');
            $("#deviceModelSpan").html(data.data.deviceModel || '');
            $("#snSpan").html(data.data.sn || '');
            $("#lastUpkeepDateSpan").html(data.data.lastUpkeepDate || '');
            $("#manufacturerNameSpan").html(data.data.manufacturerName || '');
            $("#manufacturerContactsSpan").html(data.data.manufacturerContacts || '');//厂商联系人
            $("#manufacturerPhoneSpan").html(data.data.manufacturerPhone || '');
            $("#InsideOutsideStrSpan").html(data.data.guaranteeStatus || '');
            $("#maintainerNameSpan").html(data.data.maintainerName ||'');
            $("#maintainerContactsSpan").html(data.data.maintainerContacts ||'');
            $("#maintainerPhoneSpan").html(data.data.maintainerPhone ||'');
            $("#endGuaranteeDateSpan").html(data.data.endDate);
            if(data.data.manufacturerId){
                getAssignMaintainer(data.data.manufacturerId);
            }
        }
    })
}

//新增报修Model
$("#add-repair-modal").iziModal({
    title: "新增报修",
    headerColor: '#00c0ef',
    rtl: false,
    width: 1000,
    zindex: 1042,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {},
    onOpened: function () {
        $("#addRepairForm [name='isDispatch']").on("ifChecked",function (){
            var value = $(this).val();
            if(value == 1){
                $("#fillEngineer").show();
            }else{
                $("#fillEngineer").hide();
                $("#fillEngineer input").val("");
            }
        });
        $("#addRepairForm input[name='serviceType']").on("ifChecked",function (){
            var value = $(this).val();
            $("#maintainerDiv input").val("");
            if(value == 1103){
                $("#maintainerDiv").show();
                $("#supplierDiv").hide();
                $("#manufacturerDiv").hide();
                localServiceId = null;
            }else if(value == 1102){
                $("#manufacturerDiv").show();
                $("#maintainerDiv").hide();
                $("#supplierDiv").hide();
                localServiceId = $("#addManufacturerId").val()
            }else if(value == 1105){
                $("#manufacturerDiv").hide();
                $("#maintainerDiv").hide();
                $("#supplierDiv").show();
                localServiceId = $("#addSupplierId").val()
            }else{
                $("#manufacturerDiv").hide();
                $("#maintainerDiv").hide();
                $("#supplierDiv").hide();
                localServiceId = null;
            }
        })
    },
    onClosing: function () {},
    onClosed: function () {
        $("#addRepairForm")[0].reset();
        $("#addDeviceStatus").val("").trigger("change");
    }
});

// 分配服务商Model
$("#assign-model").iziModal({
    title: "服务商",
    headerColor: '#00c0ef',
    rtl: false,
    width: 1300,
    zindex: 1042,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    closeOnEscape:false,
    onOpening: function () {
        $("#assign-maintainer").val(null);
        $("#assign-maintainer").select2({
            language: 'zh-CN',
            placeholder: '服务商',
            allowClear: true
        });
        validator();
        if(localDeviceId){
            getDeviceInfo(localDeviceId);
        }
        $("input[name='is_dispatch'][value='0']").iCheck('check');
    },
    onOpened: function () {
        $("#assignForm input[name='serviceType']").on("ifChecked",function (){
            var value = $(this).val();
            globalServiceType = value;
            $("#assignMaintainerDiv input").val("");
            if(value == 1103){
                $("#assignMaintainerDiv").show();
                $("#assignSupplierDiv").hide();
                $("#assignManufacturerDiv").hide();
                $("#assignServiceDiv").find("[name='serviceId']").val(null);
                $("#assignForm input[value='0']").parents("label").hide();//如果是维修商必须选择指派工程师
                $("#assignForm input[value='1']").iCheck("check");
                localIsDispaxth = 1;
                $("#dispatchDiv").show();
                localIsDispaxth = 1;
            }else if(value == 1102){
                $("#assignManufacturerDiv").show();
                $("#assignMaintainerDiv").hide();
                $("#assignSupplierDiv").hide();
                var manufacturerId = $("#assignMaintainerDiv").find("[name='manufacturerId']").val();
                $("#assignServiceDiv").find("[name='serviceId']").val(manufacturerId);
                $("#assignForm input[value='0']").parents("label").show();
            }else if(value == 1105){
                $("#assignManufacturerDiv").hide();
                $("#assignMaintainerDiv").hide();
                $("#assignSupplierDiv").show();
                var supplierId = $("#assignSupplierDiv").find("[name='supplierId']").val();
                $("#assignServiceDiv").find("[name='serviceId']").val(supplierId);
                $("#assignForm input[value='0']").parents("label").show();
            }else{
                $("#assignManufacturerDiv").hide();
                $("#assignMaintainerDiv").hide();
                $("#assignSupplierDiv").hide();
                $("#assignServiceDiv").find("[name='serviceId']").val(null);
            }
    }   );

        $("[name='is_dispatch']").on("ifChecked",function (){
        var value = $(this).val();
        localIsDispaxth = value;
        if(value == 1){
            $("#dispatchDiv").show();
            engineerNameV = hospitalContactsV = dispathTimeV = notEmptyValid;
            engineerPhoneV = {
                validators: {
                    regexp: {
                        regexp: /^1[3|4|5|7|8][0-9]\d{8}$/,
                        message: '请填写正确的手机号码'
                    }
                }
            }

            hospitalPhoneV = {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                        regexp: /^1[3|4|5|7|8][0-9]\d{8}$/,
                        message: '请填写正确的手机号码'
                    }
                }
            }
        }else{
            $("#dispatchDiv").hide();
            engineerNameV = null;
            hospitalContactsV = null;
            dispathTimeV = null;
            engineerPhoneV = null;
            hospitalPhoneV = null;
        }
    });
    },
    onClosing: function () {},
    onClosed: function () {
        $('#assignForm')[0].reset();
        $("#assignForm").data('bootstrapValidator').destroy();
        $('#assign-model').find('#faultDepictHospital').val('');
    }
});
$("#assign_model_Two").iziModal({
    title: "维修处理",
    headerColor: '#00c0ef',
    rtl: false,
    width: 1300,
    height:600,
    zindex: 1042,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    // openFullscreen:true,
    closeOnEscape:false,
    onOpening: function () {
        $('#assign_model_Two select').select2({language: 'zh-CN', placeholder: '请选择'});
        get_ManufacturerList();
        get_MaintainerList();
    },
    onOpened: function () {
        $("#assign_model_Two [name='serviceType']").on("ifChecked",function (){
            var value = $(this).val();
            if(value == 1102){
                $(".box_one").show();
                $(".box_two").hide();
            }else{
                $(".box_two").show();
                $(".box_one").hide();
            }
        });
        $("#assign_model_Two [name='is_dispatch']").on("ifChecked",function (){
            var value = $(this).val();
            if(value == 1){
                $("#dispatch_Div").show();
            }else{
                $("#dispatch_Div").hide();
            }
        });


        $("#assign_model_Two #Manufacturer_select").on('change',function () {
            var id  = $(this).val();
            var obj = Manufacturer_select.filter(function (key,item) {
                return id == key.manufacturerId
            })
            console.log(obj[0].manufacturerContacts)
            $('.box_one').find('#Manufacturer_Linkman').text(obj[0].manufacturerContacts);
            $('.box_one').find('#Manufacturer_Phone').text(obj[0].manufacturerPhone);
            $('.box_one').find('#userName').text(obj[0].userName);
            console.log(obj);


            if(obj[0].userName == null){
                $('.box_one').find('#password').text(obj[0].password);
            }else {
                $('.box_one').find('#password').text(123456);
            }
        })

        $("#assign_model_Two #Maintainer_select").on('change',function () {
            var id  = $(this).val();
            var obj = Maintainer_select.filter(function (key,item) {
                return id == key.maintainerId
            })
            console.log(obj)
            $('.box_two').find('#Maintainer_Linkman').text(obj[0].maintainerContacts);
            $('.box_two').find('#Maintainer_Phone').text(obj[0].maintainerPhone);
            $('.box_two').find('#userName').text(obj[0].userName);


            if(obj[0].userName == null){
                $('.box_two').find('#password').text(obj[0].password);
            }else {
                $('.box_two').find('#password').text(123456);
            }



        })


    },
    onClosing: function () {},
    onClosed: function () {
        $('#assign_model_Two').find('#faultDepictHospital_Two').html('');
        $('#assign_model_Two').find('.box_img_two').html('');
        $('#assign_model_Two').find('.box_img_two').html('');
        $('#box_one').find('#Manufacturer_Linkman').text('');
        $('#box_one').find('#Manufacturer_Phone').text('');
        $('#box_one').find('#userName').text('');
        $('#box_one').find('#password').text('');
        $('#box_two').find('#Maintainer_Linkman').text('');
        $('#box_two').find('#Maintainer_Phone').text('');
        $('#box_two').find('#userName').text('');
        $('#box_two').find('#password').text('');
        $('#assign_model_Two').find('[name="engineerName"]').val('');
        $('#assign_model_Two').find('[name="engineerPhone"]').val('');
        $("#assign_model_Two #Manufacturer_select").unbind();
        $("#assign_model_Two #Maintainer_select").unbind();
    }
});

// 信息补全
$("#improve-model").iziModal({
    title: "信息补全",
    headerColor: '#00c0ef',
    rtl: false,
    width: 650,
    zindex: 1042,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {
        validator3()
    },
    onOpened: function () {},
    onClosing: function () {},
    onClosed: function () {
        $('#improve-form')[0].reset();
        $("#repairMode,#repairDeviceStartStatus,#repairDeviceEndStatus").val("").trigger("change");
        $("#improve-form").data('bootstrapValidator').destroy();
        $('#improve-one')[0].reset();
        $('#improve-two')[0].reset();
        $('#improve-three')[0].reset();
    }
});

// 确认维修Model
$("#event-model").iziModal({
    title: "添加事件",
    headerColor: '#00c0ef',
    rtl: false,
    width: 650,
    zindex: 1042,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {
        validator2();
    },
    onOpened: function () {},
    onClosing: function () {},
    onClosed: function () {
        $('#event-form')[0].reset();
        $("#event-form").data('bootstrapValidator').destroy();
    }
});

//修改负责人模态框
$("#edit-responser-model").iziModal({
    title: "修改负责人",
    headerColor: '#00c0ef',
    rtl: false,
    width: 650,
    zindex: 1042,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {
    },
    onOpened: function () {},
    onClosing: function () {},
    onClosed: function () {
        $('#edit-responser-form')[0].reset();
    }
});

$("#part-modal").iziModal({
    title: "备件列表",
    headerColor: '#00c0ef',
    rtl: false,
    width: 1200,
    padding: 0,
    radius: 3,
    zindex: 1043,
    focusInput: false,
    group: '',
    loop: false,
    navigateCaption: true,
    navigateArrows: true, // closeToModal, closeScreenEdge
    history: false,
    restoreDefaultContent: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: false,
    fullscreen: true,
    openFullscreen: false,
    closeOnEscape: false,
    overlay: true,
    overlayClose: false,
    overlayColor: 'rgba(0, 0, 0, 0.4)',
    onOpening: function () {},
    onOpened: function () {},
    onClosing: function () {
        partMap = new Map();
    },
    onClosed: function () {}
});

$("#addPart-modal").iziModal({
    title: "新增备件",
    headerColor: "#00c0ef",
    overlayClose:true,
    autoOpen:false,
    history:false,
    zindex: 9999,
    width:1000,
    focusInput: false,
    bodyOverflow: true,
    fullscreen: true,
    openFullscreen: false,
    closeOnEscape: true,
    overlay: true,
    overlayClose: false,
    onOpening: function () {},
    onOpened: function () {
        $("input[name='partExplain'][value='2001']").on("ifChecked",function(){
            $("#newDiv").removeClass("hide");
            $("#oldDiv").addClass("hide");
            $("#oldDiv input").val("");
        })

        $("input[name='partExplain'][value='2000']").on("ifChecked",function(){
            $("#newDiv").removeClass("hide");
            $("#oldDiv").removeClass("hide");
            $("#newDiv input, #oldDiv input").val("");
        })

        $("input[name='partExplain'][value='2002']").on("ifChecked",function(){
            $("#newDiv").addClass("hide");
            $("#oldDiv").removeClass("hide");
            $("#newDiv input").val("");
        })
        $("#oldFileForm input[name='keyType'],#newFileForm input[name='keyType']").val("1407");
        $("#oldFileForm input[name='fileType']").val("3404");
        $("#newFileForm input[name='fileType']").val("3403");
    },
    onClosing: function () {
        clearAddPartForm();
        $("#oldFileForm")[0].reset();
        $("#newFileForm")[0].reset();
    },
    onClosed: function () {}
});

// 审核维修商
$("#examine-maintainer").iziModal({
    title: "审核维修商",
    headerColor: '#00c0ef',
    rtl: false,
    width: 800,
    zindex: 1044,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {
        $("input[name='examine']").iCheck({
            checkboxClass: 'icheckbox_flat-green',
            radioClass: 'iradio_flat-green'
        });
        $("#examine-maintainer-form input[value='1']").iCheck("check");
    },
    onOpened: function () {},
    onClosing: function () {
        $('#examine-maintainer-form')[0].reset();
    },
    onClosed: function () {
        
    }
});

function bindServiceInfo(upkeepId,serviceName,serviceContacts,servicePhone){
    $("#examine-maintainer-form").find("[name='serviceName']").val(serviceName);
    $("#examine-maintainer-form").find("[name='serviceContacts']").val(serviceContacts);
    $("#examine-maintainer-form").find("[name='servicePhone']").val(servicePhone);
    $("#examine-maintainer-form").find("[name='repairId']").val(localRepairId);
    $("#examine-maintainer").iziModal("open",this);
}

function saveExamineMaintainer(){
    isCheckMaintainer = false;
    $("#serviceCompanySpan button").remove();
    if($("#examine-maintainer-form input[name='examine']:checked").val() == 1){//审核通过
        publicAjax(apiUrl+"repair/agree","POST",$("#examine-maintainer-form"),function (data) {
            if(data.ret ==200){
                $("#examine-maintainer").iziModal("close",this);
                getBaseInfo();
            }else{
                flavrShowByTime(data.msg,null,"danger",false);
            }
        })
    }else{//审核不通过,重新选择服务商
        publicAjax(apiUrl+"repair/disagree","POST",{repairId: localRepairId, examineComment: $("#examine-maintainer-form input[name='examineComment']").val()},function (data) {
            if(data.ret ==200){
                $("#assignForm input[value='1102']").parents("label").show();
                $("#assignForm input[value='1103']").parents("label").show();
                $("#assignForm input[value='1105']").parents("label").show();
                $("#examine-maintainer").iziModal("close",this);
                getBaseInfo();
            }else{
                flavrShowByTime(data.msg,null,"danger",false);
            }
        })
        
    }   
}

function createRepair(){
    $("#add-repair-modal").iziModal("open",this);
    if($("#userName").val() && userType !=1104){
        $("#addRepairPerson").val($("#userName").val());
    }
    if($("#userPhone").val() && userType !=1104){
        $("#addRepairPhone").val($("#userPhone").val());
    }
}

function confirm(){
    if($("input[name='one']:checked").length){
        localRepairId = $("input[name='one']:checked").val();
        localDeviceId = $("input[name='one']:checked").attr("deviceId");
        localStatus = $("input[name='one']:checked").attr("status");
        if(localStatus == "2203"){//只能是待确认状态下才能确认
            $("#confirmDiv").confirmData({
                keyType:2901,
                keyId: localRepairId,
                root: apiUrl,
                confirmUrl: "repair/confirm",
                typeStatus: 1,
                callback: function(obj){
                    var isSuccess = obj.returnIsSuccess();
                    if(isSuccess){
                        flavrShowByTime("操作成功",null,"success",null);
                        getRepairList();
                    }else{
                        flavrShowByTime("操作失败",null,"success",null);
                    }
                }
            });
        }else{
            flavrShowByTime("只能是待确认状态下才能确认",null,"danger",null);
        }
    }else{
        flavrShowByTime("请选择一条维修记录",null,"danger",null);
    }
}

function addEvent(){
    if($("input[name='one']:checked").length){
        localRepairId = $("input[name='one']:checked").val();
        localDeviceId = $("input[name='one']:checked").attr("deviceId");
        localStatus = $("input[name='one']:checked").attr("status");
        $("#event-model").iziModal("open",this);
        var json = {keyType:1601, keyId: localRepairId,type:"event",root:apiUrl};
        $("#saveEventDiv").eventData(json);
    }else{
        flavrShowByTime("请选择一条维修记录",null,"danger",null);
    }
}

function editResponsier(){
    if($("input[name='one']:checked").length){
        localRepairId = $("input[name='one']:checked").val();
        localDeviceId = $("input[name='one']:checked").attr("deviceId");
        localStatus = $("input[name='one']:checked").attr("status");
        if(localStatus == 2206 || localStatus == 2202 || localStatus == 2201){//只有待维修、待工程师确认和待指派的状态下才可以修改负责人
            /*$("#edit-responser-form input[name='repairId']").val(localRepairId);*/
            publicAjax(apiUrl+"repair/details","POST",{repairId: localRepairId},function(data){
                if(data.ret == 200){
                    if(data.data.appointView){
                        $("#editEngineerName").val(data.data.appointView.engineerName || '');
                        $("#editEngineerPhone").val(data.data.appointView.engineerPhone || '');
                        $("#edit-responser-form input[name='appointId']").val(data.data.appointView.appointId || '');
                    }
                }
            })
            $("#edit-responser-model").iziModal("open",this);
        }else{
            flavrShowByTime("该状态下不能修改负责人",null,"danger",null);
        }
        
    }else{
        flavrShowByTime("请选择一条维修记录",null,"danger",null);
    }
}
//提交修改负责人
function editConfirm(){
    var canEditConfirm = true,editError = '';
    var phoneValid = /^1[3|4|5|7|8][0-9]\d{8}$/
    if(!$("#editEngineerName").val()){
        canEditConfirm = false;
        editError = "请填写工程师姓名";
    }else if(!$("#editEngineerPhone").val()){
        canEditConfirm = false;
        editError = "请填写工程师电话";
    }else if(!(phoneValid.test($("#editEngineerPhone").val()))){
        canEditConfirm = false;
        editError = "工程师电话无效";
    }else{
        publicAjax(apiUrl+"repair/editEngineer","POST",$("#edit-responser-form"),function(data){
            if(data.ret == 200){
                flavrShowByTime("操作成功",null,"success",null);
                $("#edit-responser-model").iziModal("close",this);
                getRepairList();
            }else{
                flavrShowByTime(data.msg,null,"danger",null);
            }
        })
    }
}

function queryPartListByRepairId(){
    if($("input[name='one']:checked").length){
        localRepairId = $("input[name='one']:checked").val();
        localDeviceId = $("input[name='one']:checked").attr("deviceId");
        localStatus = $("input[name='one']:checked").attr("status");
        $("#part-modal").find("[name='repairId']").val(localRepairId);
        var url = apiUrl+"base/queryPartList";
        publicAjax(url,"POST",{keyId:localRepairId,keyType:1901},function (data){
            if(data.ret == 200){
                bindPartListData(data.data);
            }else{
                flavrShowByTime(data.msg,null,"danger",false);
            }
        });
    }else{
        flavrShowByTime("请选择一条维修", null, "danger", false);
        return;
    }
}

var partMap = new Map();
function bindPartListData(obj){
    var str =  "";
    if(obj == null || obj.length == 0){
        str = "<tr><td class='text-muted text-center' colspan='15'>暂无数据</td></tr>";
    }else{
        $.each(obj,function (index,item){
            var oldFileLength = item.oldFileList == null ? 0 : item.oldFileList.length;
            var newFileLength = item.newFileList == null ? 0 : item.newFileList.length;
            str+= "<tr>" +
                "<td class='ext-muted text-center'><button type='button' class='btn btn-danger btn-xs' data-toggle='tooltip' title='删除' onclick='deletePart("+item.partId+",this)'><i class='fa fa-times'></i></button></td>" +
                "<td class='ext-muted text-center'>"+(item.partExplainName || '')+"</td>" +
                "<td class='ext-muted text-center'>"+(item.oldPartName || '')+"</td>" +
                "<td class='ext-muted text-center'>"+(item.oldPartBrand || '')+"</td>" +
                "<td class='ext-muted text-center'>"+(item.oldPartModel || '')+"</td>" +
                "<td class='ext-muted text-center'>"+(item.oldPartSn || '')+"</td>" +
                "<td class='ext-muted text-center'>"+(item.oldPartPrice ? item.oldPartPrice/100 : '')+"</td>" +
                "<td class='ext-muted text-center'>"+(item.newPartName || '')+"</td>" +
                "<td class='ext-muted text-center'>"+(item.newPartBrand || '')+"</td>" +
                "<td class='ext-muted text-center'>"+(item.newPartModel || '')+"</td>" +
                "<td class='ext-muted text-center'>"+(item.newPartSn || '')+"</td>" +
                "<td class='ext-muted text-center'>"+(item.newPartPrice ? item.newPartPrice/100 : '')+"</td>" +
                "<td class='ext-muted text-center'><a href='javascript:showPartFile("+item.partId+",1)'>"+oldFileLength+"</a></td>" +
                "<td class='ext-muted text-center'><a href='javascript:showPartFile("+item.partId+",2)'>"+newFileLength+"</a></td>" +
                "<td class='ext-muted text-center'>"+(item.remark || '')+"</td>" +
                "</tr>";
            item.flag = 2;  //操作：1是新增，2是修改(暂时不提供修改功能)，3是删除
            partMap.put(item.partId,item);
        });
    }
    $("#part_list").html(str);
    $("#part-modal").iziModal("open",this);
}

function deletePart(id,obj){
        if(partMap.get(id).partId != null && partMap.get(id).partId != ""){
            partMap.get(id).flag = 3;
        }else{
            partMap.remove(id);
        }
        $(obj).parent().parent().remove();
}

var  count = 0
/*function addPartInfo(){
    var reg = /^[0-9]\d*(\.\d{1,2})?$/;
    var oldPartPrice = $("#addPartForm").find("[name='oldPartPrice']").val();
    if(oldPartPrice != null && oldPartPrice != ''){
        if(!reg.test(oldPartPrice)){
            flavrShowByTime("请输入正确格式的旧备件价格。",null,"danger",false);
            return;
        }else{
            oldPartPrice = oldPartPrice *100;
        }
    }
    var newPartPrice = $("#addPartForm").find("[name='newPartPrice']").val();
    if(newPartPrice != null && newPartPrice != ''){
        if(!reg.test(newPartPrice)){
            flavrShowByTime("请输入正确格式的新备件价格。",null,"danger",false);
            return;
        }else{
            newPartPrice = newPartPrice *100;
        }
    }
    var oldPartName = $("#addPartForm").find("[name='oldPartName']").val();
    var oldPartBrand = $("#addPartForm").find("[name='oldPartBrand']").val();
    var oldPartModel = $("#addPartForm").find("[name='oldPartModel']").val();
    var oldPartSn = $("#addPartForm").find("[name='oldPartSn']").val();
    var newPartName = $("#addPartForm").find("[name='newPartName']").val();
    var newPartBrand = $("#addPartForm").find("[name='newPartBrand']").val();
    var newPartModel = $("#addPartForm").find("[name='newPartModel']").val();
    var newPartSn = $("#addPartForm").find("[name='newPartSn']").val();
    var remark = $("#addPartForm").find("[name='remark']").val();
    var  partExplain = $('input[name="partExplain"]:checked').val();
    var partExplainName = "";
    if(partExplain == 2001){
        partExplainName = "新增";
    }else if(partExplain == 2000){
        partExplainName = "更换";
    }else if(partExplain == 2002){
        partExplainName = "收回";
    }
    var item = {};
    item.oldPartName = oldPartName;
    item.oldPartBrand = oldPartBrand;
    item.oldPartModel = oldPartModel;
    item.oldPartSn = oldPartSn;
    item.newPartName = newPartName;
    item.newPartBrand = newPartBrand;
    item.newPartModel = newPartModel;
    item.newPartSn = newPartSn;
    item.remark = remark;
    item.oldPartPrice = oldPartPrice;
    item.newPartPrice = newPartPrice;
    item.flag = 1;
    item.partExplain = partExplain;
    item.partExplainName = partExplainName;
    partMap.put(count,item);
    showaddPart(item,count);
    count++;
}
*/
function addPartInfo(oldPartPrice,newPartPrice,oldFileList,newFileList){
        var item = {};
        var oldPartName = $("#addPart-modal").find("[name='oldPartName']").val();
        var oldPartBrand = $("#addPart-modal").find("[name='oldPartBrand']").val();
        var oldPartModel = $("#addPart-modal").find("[name='oldPartModel']").val();
        var oldPartSn = $("#addPart-modal").find("[name='oldPartSn']").val();
        var newPartName = $("#addPart-modal").find("[name='newPartName']").val();
        var newPartBrand = $("#addPart-modal").find("[name='newPartBrand']").val();
        var newPartModel = $("#addPart-modal").find("[name='newPartModel']").val();
        var newPartSn = $("#addPart-modal").find("[name='newPartSn']").val();
        var remark = $("#addPart-modal").find("[name='remark']").val();
        var  partExplain = $('input[name="partExplain"]:checked').val();
        var partExplainName = "";
        if(partExplain == 2001){
            partExplainName = "新增";
        }else if(partExplain == 2000){
            partExplainName = "更换";
        }else if(partExplain == 2002){
            partExplainName = "收回";
        }

        if(partExplain == 2001 || partExplain == 2000){
            item.newPartName = newPartName;
            item.newPartBrand = newPartBrand;
            item.newPartModel = newPartModel;
            item.newPartSn = newPartSn;
            item.newPartPrice = newPartPrice;
            item.newFileList = newFileList;
        }
        if(partExplain == 2002 || partExplain == 2000){
            item.oldPartName = oldPartName;
            item.oldPartBrand = oldPartBrand;
            item.oldPartModel = oldPartModel;
            item.oldPartSn = oldPartSn;
            item.oldPartPrice = oldPartPrice;
            item.oldFileList = oldFileList;
        }
        item.remark = remark;
        item.flag = 1;
        item.partExplain = partExplain;
        item.partExplainName = partExplainName;
        partMap.put(count,item);
        showaddPart(item,count);
        count++;
}

function showaddPart(item,index){
    var oldFileLength = item.oldFileList == null ? 0: item.oldFileList.length;
    var newFileLength = item.newFileList == null ? 0: item.newFileList.length;
    var str = "<tr>" +
       "<td class='ext-muted text-center'><button type='button' class='btn btn-danger btn-xs' data-toggle='tooltip' title='删除' onclick='deletePart("+index+",this)'><i class='fa fa-times'></i></button></td>" +
        "<td class='ext-muted text-center'>"+(item.partExplainName== null ? '':item.partExplainName )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.oldPartName== null ? '':item.oldPartName )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.oldPartBrand== null ? '':item.oldPartBrand )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.oldPartModel== null ? '':item.oldPartModel )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.oldPartSn== null ? '':item.oldPartSn )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.oldPartPrice== null ? '':item.oldPartPrice /100)+"</td>" +
        "<td class='ext-muted text-center'>"+(item.newPartName== null ? '':item.newPartName )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.newPartBrand== null ? '':item.newPartBrand )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.newPartModel== null ? '':item.newPartModel )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.newPartSn== null ? '':item.newPartSn )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.newPartPrice== null ? '':item.newPartPrice /100)+"</td>" +
        "<td class='ext-muted text-center'><a href='javascript:showPartFile("+index+",1)'>"+oldFileLength+"</a></td>" +
        "<td class='ext-muted text-center'><a href='javascript:showPartFile("+index+",2)'>"+newFileLength+"</a></td>" +
        "<td class='ext-muted text-center'>"+(item.remark== null ? '':item.remark )+"</td>" +
        "</tr>";
    if(partMap.size() == 1){
        $("#part_list").html(str);
    }else{
        $("#part_list").append(str);
    }

    $("#addPart-modal").iziModal("close",this);
}

function showPartFile(id,type){
    $("#oldFileImgDiv").html("");
    $("#newFileImgDiv").html("");
    var fileList;
    if(type == 1){
        fileList = partMap.get(id).oldFileList;
    }else{
        fileList = partMap.get(id).newFileList;
    }
    if(fileList == null){
        return;
    }else{
        $.each(fileList,function (index,item){
            if(type == 1){
                $("#oldFileImgDiv").append("<img style='width:45%' height='400px;' src='"+item.fileUrl+"'/>");
                $("#newFileDiv").hide();
                $("#oldFileDiv").show();
            }else{
                $("#newFileImgDiv").append("<img style='width:45%' height='400px;' src='"+item.fileUrl+"'/>");
                $("#oldFileDiv").hide();
                $("#newFileDiv").show();
            }
        });
    }

    $("#showFileDiv").find("img").viewer("destroy");
    $("#showFileDiv").find("img").viewer();
    $("#showFileDiv").iziModal("open",this);
}

function clearAddPartForm(){
    $("#addPart-modal").find("[name='oldPartName']").val("");
    $("#addPart-modal").find("[name='oldPartBrand']").val("");
    $("#addPart-modal").find("[name='oldPartModel']").val("");
    $("#addPart-modal").find("[name='oldPartPrice']").val("");
    $("#addPart-modal").find("[name='oldPartSn']").val("");
    $("#addPart-modal").find("[name='files']").val("");
    $("#addPart-modal").find("[name='newPartName']").val("");
    $("#addPart-modal").find("[name='newPartBrand']").val("");
    $("#addPart-modal").find("[name='newPartModel']").val("");
    $("#addPart-modal").find("[name='newPartSn']").val("");
    $("#addPart-modal").find("[name='newPartPrice']").val("");
    $("#addPart-modal").find("[name='remark']").val("");
}

function savePart(){
    var keyId =  $("#part-modal").find("[name='repairId']").val();
    console.log(JSON.stringify(partMap));
    if(partMap.size()  ==  0){
        $("#part-modal").iziModal("close",this);
        return;
    }else{
        var array = new Array();
        partMap.each(function (key,value,index) {
            array.push(value);
        })
        var partList = JSON.stringify(array);
        var url = apiUrl+"part/savePartByBatch";
        var json = {};
        json.partList = partList;
        json.keyId = keyId;
        json.keyType = 1901;
        publicAjax(url,"POST",json,function (data){
            if(data.ret == 200){
                flavrShowByTime(data.msg,null,"success",false);
                $("#part-modal").iziModal("close",this);
            }else{
                flavrShowByTime(data.msg,null,"danger",false);
            }
        });
    }
}

function getRepairList(){
    $("#repair-table").html("");
    filterData = {
        start: 0,
        end: $("#show-count").val(),
        hospitalId: $("#filter-hospital").val(),
        allName: $("#deviceName").val(),
        repairNo: $("#filterRepairNo").val(),
        serviceId: $("#filter-maintainer").val(),
        status: $("#filter-status").val()
    }
    publicAjax(apiUrl+"repair/list","POST",filterData,function (data) {
        if(data.ret == 200){
            $("#total-count").text(data.data.count);
            if(data.data.count){
                $.each(data.data.list, function(index, item){
                    $("#repair-table").append("<tr>\
                        <td>"+(index+1)+"</td>\
                        <td class='text-center text-muted'>\
                            <input type='checkbox' class='flat-green' deviceId='"+item.deviceId+"' status='"+item.status+"' name='one' value='"+item.repairId+"'>\
                        </td>\
                        <td class='text-center text-muted'><button type='button' class='btn btn-primary btn-xs' onclick='queryRepairInfo("+item.repairId+")' data-original-title='详情'><i class='fa fa-file-text-o'></i></button></td>\
                        <td class='text-muted'>"+(item.repairNo || '')+"</td>\
                        <td class='text-muted'>"+(item.deviceName || '')+"</td>\
                        <td class='text-muted'>"+(item.deviceModel || '')+"</td>\
                        <td class='text-muted'>"+(item.sn || '')+"</td>\
                        <td class='text-muted'>"+(item.hospitalName || '')+"</td>\
                        <td class='text-muted'>"+(item.repairPerson || '')+"</td>\
                        <td class='text-muted'>"+(item.repairPersonPhone || '')+"</td>\
                        <td class='text-muted'>"+(item.maintainerName || '')+"</td>\
                        <td class='text-muted'>"+(item.statusStr || '')+"</td>\
                        <td class='text-muted'>"+(item.commentStatusName || '')+"</td>\
                    </tr>")
                })
                initDomCss();
            }else{
                $("#repair-table").html("<tr><td class='text-center text-muted' colspan='15'>暂无维修信息</td></tr>");
                initDomCss();
            }
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    })
}

function initDomCss(){
    $('input.flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

    $("input[name='one']").on('ifChecked', function(event){
        var current = $(this).parents("tr").index();
        $("[name='one']:checked").each(function(i){
            if($(this).parents("tr").index()!=current){
                $(this).iCheck('uncheck');
            }
        });
    });
    $("#assignForm").find("input[name='dispathTime']").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        minuteStep:1,
        todayBtn: true
    }).on('hide',function(e) {
        $('#assignForm').data('bootstrapValidator')
            .updateStatus('dispathTime', 'NOT_VALIDATED',null)
            .validateField('dispathTime');
    });

    $("#eventDateTime").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        minuteStep:1,
        todayBtn: true
    }).on('hide',function(e) {
        $('#event-form').data('bootstrapValidator')
            .updateStatus('eventDateTime', 'NOT_VALIDATED',null)
            .validateField('eventDateTime');
    });

    $("#repairEndTime,#faultTime").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        minuteStep:1,
        todayBtn: true
    })

    $("#repairMode,#repairDeviceStartStatus,#repairDeviceEndStatus").val(null);
    $("#repairMode,#repairDeviceStartStatus,#repairDeviceEndStatus,#addDeviceStatus,select[name='fileType']").select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true
    });
    $("select[name='fileType']").select2({
        language: 'zh-CN',
        placeholder: '请选择',
    });
}

function initQueryTerm(){
    var url = apiUrl+"/base/queryHosital";
    $("#filter-hospital").html("");
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.hospitalId+"'>"+item.hospitalName+"</option>";
            });

            $("#queryForm select[name='hospitalId']").html(html);
            $("#queryForm select[name='hospitalId']").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });

    url = apiUrl + "/base/queryManufacturer";
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.manufacturerId+"'>"+item.manufacturerName+"</option>";
            });
            $("#filter-manufacturer").html(html);
            $("#filter-manufacturer").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });

    url = apiUrl + "/base/queryMaintainer";
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.maintainerId+"'>"+item.maintainerName+"</option>";
            });
            $("#filter-maintainer").html(html);
            $("#filter-maintainer").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });

    $("#filter-status").html("");
    url = apiUrl + "/base/queryItem";
    publicAjax(url,"POST",{type:'repair_status'},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.itemId+"'>"+item.item+"</option>";
            });
            $("#filter-status").html(html);
            $("#filter-status").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}
//获取分配时的维修商
function getAssignMaintainer(mId){
    publicAjax(apiUrl+"base/queryMinListByMamuId","POST",{manufacturerId: mId},function (data) {
        if(data.ret == 200){
            var html = "<option value=''></option>";
            $.each(data.data,function (index,item) {
                var isSelected = "";
                if(item.manufacturer){
                    isSelected = "selected";
                }
                html += "<option value='"+item.maintainerId+"' "+isSelected+">"+item.maintainerName+"</option>";
            });
            $("#assign-maintainer").html(html);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}

function refresh(){
    window.location.reload();
}

function search(){
    getRepairList();
}

function queryRepairInfo(id){
    location.href = apiUrl+"repair/info?id="+id;
}
var assignMaintainerV,engineerNameV,hospitalContactsV,dispathTimeV,engineerPhoneV,hospitalPhoneV;
var notEmptyValid = {
    validators: {
        notEmpty: {
            message: '不能为空'
        }
    }
}
var assignMaintainerV = engineerNameV = hospitalContactsV = dispathTimeV = notEmptyValid;
engineerPhoneV = {
    validators: {
        regexp: {
            regexp: /^1[3|4|5|7|8][0-9]\d{8}$/,
            message: '请填写正确的手机号码'
        }
    }
}

hospitalPhoneV = {
    validators: {
        notEmpty: {
            message: '不能为空'
        },
        regexp: {
            regexp: /^1[3|4|5|7|8][0-9]\d{8}$/,
            message: '请填写正确的手机号码'
        }
    }
}
//分配表单校验
function validator(){
    $('#assignForm').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            assignMaintainer: assignMaintainerV,
            engineerName: engineerNameV,
            hospitalContacts: hospitalContactsV,
            engineerPhone: engineerPhoneV,
            hospitalPhone: hospitalPhoneV
            /*dispathTime: dispathTimeV*/
        }
    });
}
//添加时间表单校验
function validator2(){
    $('#event-form').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            eventTitle: notEmptyValid,
            eventDateTime: notEmptyValid,
            eventContent: notEmptyValid
        }
    });
}

//信息补全校验
function validator3(){
    $('#improve-form').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            repairDeviceEndStatus: notEmptyValid,
            travelTime: {
                validators: {
                    regexp: {
                        regexp: /^\d+(?:\.\d{1,2})?$/,
                        message: '只能输入数字，且最多保留两位小数'
                    }
                }
            }
        }
    });
}



function engineerNameBlur(obj) {
    if($(obj).val().trim() == null || $(obj).val().trim() == ""){
        return;
    }

    var maintainerId = $("#assign-maintainer").val();
    if(maintainerId == null || maintainerId == ""){
        flavrShowByTime("请选择服务商",null,"danger",false);
        return;
    }

    var json = {maintainerId:maintainerId,engineerName:$(obj).val().trim()}

    var url = apiUrl+"/upkeep/queryEngineerPhoneByName";
    publicAjax(url,"POST",json,function (data){
        if(data.ret == 200){
            $("#assign-model").find("[name='engineerPhone']").val(data.data || '');
        }
    });
}

$('input[name=files]').fileinput({
    language: 'zh', //设置语言
    enctype: 'multipart/form-data',
    showUpload: false, //是否显示上传按钮
    showCaption: false,//是否显示标题
    browseClass: "btn btn-info", //按钮样式
    msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
});

